package com.denso.store.admin.scheduler;

import com.denso.store.common.AdminOpt;
import com.denso.store.common.Tools;
import com.denso.store.common.model.Scheduler;
import com.jfinal.core.Controller;

import java.util.Date;
import java.util.List;

/**
 * Created by lijian on 2017/10/22.
 */
public class SchedulerController extends Controller {

    static SchedulerService service = new SchedulerService();

    public void index() {
        List<Scheduler> schedulerList = service.findAll();
        setAttr("schedulerList", schedulerList);
        render("index.html");
    }

    public void add() {
        render("add.html");
    }

    public void save() {
        Scheduler scheduler = getModel(Scheduler.class);

        // 根据页面传递的小时分钟设置计划入库时间(当天)
        int hour = getParaToInt("hour");
        int minute = getParaToInt("minute");
        Date planTime = Tools.convertDate(hour, minute);
        scheduler.setPlanTime(planTime);

        String admin = getSessionAttr("admin");
        scheduler.setAdmin(admin);

        // 是否为额外添加任务
        String extra = getPara("extra", "false");
        if(extra.equalsIgnoreCase("true")) {
            scheduler.setAdminOpt(AdminOpt.EXTRA);
        } else {
            scheduler.setAdminOpt(AdminOpt.NORMAL);
        }

        service.save(scheduler);
        setAttr("notice", "添加成功");
        index();
    }

    public void edit() {
        int id = getParaToInt("id");
        Scheduler scheduler = service.findById(id);
        setAttr("scheduler", scheduler);
        render("edit.html");
    }

    public void update() {
        Scheduler scheduler = getModel(Scheduler.class);

        int hour = getParaToInt("hour");
        int minute = getParaToInt("minute");
        Date planTime = Tools.convertDate(hour, minute);
        scheduler.setPlanTime(planTime);

        String admin = getSessionAttr("admin");
        scheduler.setAdmin(admin);


        service.update(scheduler);
        setAttr("notice", "修改成功");
        index();
    }

    public void delete() {
        int id = getParaToInt("id");
        service.deleteById(id);
        setAttr("notice", "删除成功");
        index();
    }

    public void cancel() {
        int id = getParaToInt("id");
        String admin = getSessionAttr("admin");
        service.cancel(id, admin);
        setAttr("notice", "取消成功");
        index();
    }
}
